import axios from 'axios'

const baseURL = typeof window === 'undefined' ? process.env.API_SERVER : ''

const http = axios.create({
  baseURL,
  validateStatus: status => status < 500
})

// 请求拦截
http.interceptors.request.use(
  (config) => {
    // console.log("请求头: ", config.headers);
    return config;
  },
  (error) => {}
);

// 响应拦截
http.interceptors.response.use(
  (res) => {
    // 请求成功
    // console.log("响应拦截器-res: ", res);
    console.log("响应拦截器-res.data(响应体): ", res.data);
    if(res.data.code === 40001 || res.data.code === 40002) {
      window.location.href = '/auth/login';
    }
    return res;
  },
  (error) => {
    // 请求失败(服务器报错)
    console.log("响应拦截器-error: ", error);
    console.log("响应拦截器-error.response: ", error.response);
    console.log("响应拦截器-error.response.data: ", error.response.data);
    if(error.response.data.code !== 0) {
      console.log(error.response.data.message);
    }
    // 返回请求失败(后端报错)的相关参数
    return error.response;
  }
);

export default http;
